from typing import Any, List, Dict

from fastapi import APIRouter

from Agent.FillTable.Dao.FillTableRequest import FillTableRequest
from Agent.FillTable.Dao.FillTableResponse import FillTableResponse
from Agent.FormAnalyzer.Service.FormAnalyzerService import FormAnalyzerServiceService
from Agent.SecondBarging.Dao.SecondBargainingRequest import SecondBargainingRequest
from Agent.SecondBarging.Dao.SecondBargainingResponse import SecondBargainingResponse
from core.BaseAgent import BaseAgent
from LlmModel.DoubaoModel.DoubaoModel import DoubaoModel
from utils.logger import get_logger

logger = get_logger("FillTableService")


class FillTableService(BaseAgent):
    def __init__(self):
        super().__init__(name="FillTableService")
        self.name = "表单填写智能体"
        self.description = "负责填写二次议价所需的表单"
        self.doubao_client = DoubaoModel()
        self.formAnalyzerServiceService = FormAnalyzerServiceService()
        # self.prompt_builder = PromptBuilder()
        # self._setup_routes()
        # self.fill_chat = FillChat(self.doubao_client)

    # def _setup_routes(self) -> None:
    #     """设置路由"""
    #     router = APIRouter(prefix=f"/{self.__class__.__name__.lower().replace('agent', '')}")
    #     router.post("/fill", response_model=FillTableResponse)(self.fill_route)
    #     self.router = router

    async def checkFillTableState(self, request: SecondBargainingRequest) -> FillTableResponse:
        """
        检测表单填写的状态，根据状态分发到abc三个阶段去处理

        :param data: 包含聊天历史、用户输入和表单状态的数据
        :return: 处理结果
        """
        try:
            conversations = request.conversations
            # user_input = next((m.get('content') for m in reversed(conversations) if m.get('role') == "user"), "")

            # 提取第一个 assistant 的 content 作为 base_info
            base_info = self._extract_base_info(conversations)

            ##############################
            # 拿到总体表单abc状态
            form_status = await self._get_form_status(conversations, base_info)
            logger.info(f"表单状态标识: a={form_status['a']}, b={form_status['b']}, c={form_status['c']}")

            return FillTableResponse(
                response="",
                success=True,
                # message="选号需求填写成功",
                # status="1",  # 添加 status 字段，默认为 "1"
                # diff_info=diff_info,  # 返回差异信息
                # status_code=status_code,  # 返回状态码
                form_status=form_status,  # 这里只需要状态判断（****）
                # discount_round=0  # 返回折扣轮次
            )

        ##############################

        # if form_status.get("b") == "b2" and "empty_info" in form_status:
        #     logger.info(f"检测到空字段信息: {form_status['empty_info']}")
        #
        # # 新增：全局语义判断逻辑 - 使用提取的方法
        # status_code, diff_info = await self._extract_diff_info(conversations, user_input, base_info)
        #
        # # 记录到日志
        # logger.info(f"全局语义判断结果 - diff_info: {diff_info}, status_code: {status_code}")
        # print(f"全局语义判断结果 - diff_info: {diff_info}, status_code: {status_code}")
        #
        # # 构建提示词，传入 is_first 参数、base_info 和 diff_info
        # prompt = self.prompt_builder._build_prompt(conversations, user_input, current_form, is_first, base_info,
        #                                            diff_info)
        #
        # # 调用大模型生成回复，同时获取折扣轮次信息
        # response, discount_round = await self.fill_chat.handle_form_status(
        #     form_status, conversations, prompt, diff_info, base_info
        # )
        #
        # logger.info(f"选号需求填写完成，用户输入: {user_input[:50]}...，是否为首次: {is_first}")
        #

        except Exception as e:
            logger.error(f"状态判断失败: {str(e)}")
            return FillTableResponse(
                response="抱歉，系统暂时无法处理您的请求，请稍后再试。",
                success=False,
                message=f"状态判断失败: {str(e)}",
                status="0",  # 添加 status 字段，错误时返回 "0"
                diff_info="",
                status_code=0,
                form_status={"c": "c2"},  # 默认状态
                discount_round=0
            )

    def _extract_base_info(self, conversations: List[Dict[str, str]]) -> str:
        """
        从 conversations 中提取第一个 assistant 的 content 作为 base_info

        :param conversations: 聊天历史记录
        :return: 第一个 assistant 的 content，如果没有则返回空字符串
        """
        for message in conversations:
            if message.get("role") == "assistant":
                return message.get("content", "")
        return ""

    async def _get_form_status(self, conversations: List[Dict[str, Any]], base_info: str) -> dict[str, str]:
        """
        获取表单状态标识

        :param user_input: 用户输入
        :param base_info: 基础信息
        :return: 包含a、b、c状态标识的字典
        """
        try:
            status_result = {"a": "", "b": "", "c": ""}

            # a: 判断user_input是否与base_info同为表单形式(如果有5个以上的表单字段，认为是表单形式)  ------>注意这里的判断逻辑，可能有漏洞（如果大于5个但是小于总数，那其他的需不需要谈？）
            # 使用form_analyzer中的_is_form_like方法
            # 对conversation中user的每个对话都看一遍是不是表单，有一次是的就
            if self.formAnalyzerServiceService._is_form_like():
                status_result["a"] = "a1"
            else:
                status_result["a"] = "a2"

            # b: 判断user_input给出的表单是否完整（这部分没有用大模型，是代码判断的完整性）
            b_status, empty_info = self.formAnalyzerServiceService._check_form_completeness(user_input)
            status_result["b"] = b_status
            # 如果需要，可以将empty_info也存储在status_result中
            if b_status == "b2":
                status_result["empty_info"] = empty_info

            # c: 判断user_input是否与base_info一致
            # 复用_compare_forms方法，但调整返回结果------------------------------>这里比较的差异，只比较两个表单的折扣要求差异，应该是有15种差异
            differences = await self.formAnalyzerServiceService._compare_forms(base_info, user_input)
            if differences and "无差异" not in differences:
                status_result["c"] = "c2"
            else:
                status_result["c"] = "c1"

            return status_result

        except Exception as e:
            logger.error(f"获取表单状态失败: {str(e)}")
            # 发生错误时返回默认值
            return {"a": "a2", "b": "b2", "c": "c2"}

    async def process(self, input_data: Any) -> Any:
        pass
